package cn.cloudtogo;

import cn.cloudtogo.server.SpringTemplateContextRefreshers;
import cn.cloudtogo.server.atomapi.ExternalDatasourceGlobalApiTokenMigrator;
import cn.cloudtogo.server.module.BuiltInTableCreator;
import cn.cloudtogo.server.mysql.ExternalDatasourceUUIDMigrator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class GendbApplicationRunner implements ApplicationRunner {

    private final ApplicationContext context;

    public GendbApplicationRunner(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //init system table
        BuiltInTableCreator tableCreator = context.getBean(BuiltInTableCreator.class);
        tableCreator.createExternalDatasourceTable();
        tableCreator.createTokenManagerTable();

        //replace java uuid to objectId(mongo objectId)
        ExternalDatasourceUUIDMigrator uuidMigrator = context.getBean(ExternalDatasourceUUIDMigrator.class);
        uuidMigrator.migrate();

        //init external datasource spring template context
        SpringTemplateContextRefreshers contextRefreshers = context.getBean(SpringTemplateContextRefreshers.class);
        contextRefreshers.refresh();

        //generate global api token for old data
        ExternalDatasourceGlobalApiTokenMigrator tokenMigrator = context.getBean(ExternalDatasourceGlobalApiTokenMigrator.class);
        tokenMigrator.migrate();
    }

}
